# -*- coding:UTF-8 -*-

from django.http import HttpResponse, JsonResponse
from .models import Users
from department.models import Departments
import re
import json
from datetime import datetime
from utils.json_validate import json_validate
from utils.json_schema import *
from django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login, logout as auth_logout,authenticate
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
from django.contrib.auth.hashers import check_password
from django.core import serializers
import random
import string

# 注册
@json_validate(schema=create_user_schema)
def create_user(request):
    if request.method == 'POST':
        json_str = request.body
        json_str = json_str.decode()
        req_data = json.loads(json_str)
        print(req_data)
        if Users.objects.filter(username=req_data['username']).count() or Users.objects.filter(mobile=req_data['mobile']).count() > 0:
            data = {'success': False, 'data': {'msg': '账户或手机号已经存在'}}
            return JsonResponse(data)
        if not re.match(r'^1[3-9]\d{9}$', str(req_data['mobile'])):
            data = {'success': False, 'data': {'msg': '手机号格式错误'}}
            return JsonResponse(data)
        if req_data['password'] != req_data['password2']:
            data = {'success': False, 'data': {'msg': '两次密码不一致'}}
            return JsonResponse(data)
        # 验证码
        # if req_data['code'] != request.session.get('code'):
        #     data = {'success': False, 'data': {'msg': '验证码错误'}}
        #     return JsonResponse(data)
        # try:
        #     department = Departments.objects.get(id=req_data["department"])
        # except Exception as e:
        #     data = {'success': False, 'data': {'msg': '添加的部门不存在'}}
        #     return JsonResponse(data)
        user = Users()
        user.username = req_data['username']
        user.mobile = req_data['mobile']
        user.email = req_data['email']
        user.set_password(req_data['password'])
        user.date_joined = datetime.now()
        user.name = req_data["name"]
        # user.department = department
        user.position = req_data['position']
        user.job = req_data['job']
        user.save()

        data = {'success': True, 'data': {'msg': '注册成功',
                                          "data": {'username': user.username, 'mobile': user.mobile, "name": user.name}
                                          }}
        return JsonResponse(data)
    else:
        return HttpResponse('这是GET方法')


# 登陆
@json_validate(schema=login_schema)
def login(request):
    json_str = request.body
    json_str = json_str.decode()
    json_data = json.loads(json_str)
    username = json_data["username"]
    password = json_data["password"]
    # 验证码
    # if json_data['code'] != request.session.get('code'):
    #     data = {'success': False, 'data': {'msg': '验证码错误'}}
    #     return JsonResponse(data)
    if re.match(r'^1[3-9]\d{9}$', username):
        try:
            user_name = Users.objects.get(mobile=int(username)).username
        except Exception as e:
            return HttpResponse("账号或密码错误")
        user = authenticate(username=user_name, password=password)
    else:
        user = authenticate(username=username,password=password)
    if user is not None:
        auth_login(request, user)
        user.last_login = datetime.now()
        user.save()
        return HttpResponse("登陆")
    else:
        return HttpResponse("用户名或密码错误")


# 退出登陆
@login_required()
def logout(request):
    auth_logout(request)
    return redirect("index.html")


# 修改密码
@login_required()
@json_validate(schema=change_password_schema)
def change_password(request):
    # import pdb
    # pdb.set_trace()
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    user_name = req_data["username"]
    old_password = req_data["old_password"]
    new_password = req_data["new_password"]
    new_password2 = req_data["new_password2"]
    if new_password != new_password2:
        data = {"success": False, "data": {"msg": "请输入两次相同的新密码"}}
        return JsonResponse(data)
    user = Users.objects.filter(username=user_name)[0]
    if not check_password(old_password, user.password) or new_password == old_password:
        data = {"success": False, "data": {"msg": "原密码错误或新密码与近期使用的密码相同"}}
        return JsonResponse(data)
    user.set_password(new_password)
    user.save()
    data = {"success": True, "data": {"msg": "修改密码成功"}}
    return JsonResponse(data)


# 忘记密码
@json_validate(schema=forget_password_schema)
def forget_password(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    username = req_data["username"]
    email = req_data["email"]
    # 验证码
    if req_data['code'] != request.session.get('code'):
        data = {'success': False, 'data': {'msg': '验证码错误'}}
        return JsonResponse(data)
    if re.match(r'^1[3-9]\d{9}$', username):
        user = Users.objects.filter(mobile=username, email=email)[0]
    else:
        user = Users.objects.filter(username=username, email=email)[0]
    if not user:
        data = {"success": False, "data": {"msg": "用户名或绑定邮箱错误"}}
        return JsonResponse(data)
    new_password = ''.join(random.sample(string.ascii_letters + string.digits, 8))
    user.set_password(new_password)
    user.save()
    data = {"success": True, "data": {"msg": "密码重置为%s，请尽快更改密码" % new_password}}
    return JsonResponse(data)


# 删除员工
@login_required()
def delete_user(request):
    if request.user.is_superuser != 1:
        data = {"success": True, "data": {"msg": "你没有删除员工的权限"}}
        return JsonResponse(data)
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    username = req_data["username"]
    try:
        Users.objects.filter(username=username).delete()
        data = {"success": True, "data": {"msg": "删除员工%s成功" % username}}
    except Exception as e:
        data = {"success": False, "data": {"msg":e}}
    return JsonResponse(data)


# 查询员工
@login_required()
def get_user(request):
    users = Users.objects.all()
    # data = serializers.serialize("json", users, fields=("name", "last_login", "department_id"))
    data_list = []
    for user in users:
        dict = {}
        dict["id"] = user.id
        dict["name"] = user.name
        dict["last_login"] = user.last_login
        dict["department"] = user.department.name
        data_list.append(dict)

    data = {"success": True, "data": {"msg": "查询成功", "data": data_list}}
    print(users)
    return JsonResponse(data)


# 添加子管理员
@login_required()
@json_validate(schema=create_manager_schema)
def create_manager(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    username = req_data["username"]
    user = Users.objects.get(username=username)
    if user:
        user.is_manager = True
        user.save()


# 添加员工到制定部门
@login_required()
@json_validate(schema=add_user_to_department_schema)
def add_user_to_department(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    user_id = req_data["user_id"]
    department_id = req_data["department_id"]
    try:
        department = Departments.objects.get(id=department_id)
    except Exception as e:
        return HttpResponse("没有此部门!")
    try:
        user = Users.objects.get(id=user_id)
    except Exception as e:
        return HttpResponse("查询员工错误，请重试!")
    user.department = department
    user.save()
    data_dict = {"user_id": user.id, "name": user.name, "department_name": user.department.name}
    data = {"success": True, "data": {"msg": "添加成功", "data": data_dict}}
    return JsonResponse(data)


# 从部门中删除员工
@login_required()
@json_validate(schema=delete_user_from_department_schema)
def delete_user_from_department(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    user_id = req_data["user_id"]
    department_id = req_data["department_id"]
    try:
        user = Users.objects.get(id=user_id)
    except Exception as e:
        return HttpResponse("查询员工错误，请重试!")
    if user.department.id != department_id:
        data = {"success": False, "data": {"msg": "数据错误"}}
        return JsonResponse(data)
    user.department = Departments.objects.get(id=1)
    user.save()
    data_dict = {"user_id": user.id, "name": user.name, "department_name": user.department.name}
    data = {"success": True, "data": {"msg": "删除成功", "data": data_dict}}
    return JsonResponse(data)


# 修改员工所属部门
@login_required()
@json_validate(schema=update_user_of_department_schema)
def update_user_of_department(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    user_id = req_data["user_id"]
    department_id = req_data["department_id"]
    try:
        user = Users.objects.get(id=user_id)
    except Exception as e:
        return HttpResponse("查询员工错误，请重试!")
    if department_id == user.department.id:
        data = {"success": True, "data": {"msg": "员工已在此部门中，无需重复添加"}}
        return JsonResponse(data)
    try:
        department = Departments.objects.get(id=department_id)
    except Exception as e:
        data = {"success": True, "data": {"msg": "无此部门或查询数据出错，请重新添加。"}}
        return JsonResponse(data)
    user.department = department
    user.save()
    data = {"success": True, "data": {"msg": "添加完成。",
                                      "data": {"name": user.name, "user_id": user.id, "department_id": user.department.id,
                                               "department": user.department.name}}}
    return JsonResponse(data)





